<script lang="ts" setup>
// CommonCreateDialog 组件已通过 Vite 自动导入
import { useChannelManagement } from "./composables/useChannelManagement"
import {
  channelDialogConfig,
  editChannelDialogConfig,
  editSecondAgentDialogConfig,
  editThirdAgentDialogConfig,
  secondAgentDialogConfig,
  thirdAgentDialogConfig
} from "./configs/dialogConfigs"

// 使用业务逻辑
const {
  selectedChannel,
  searchKeyword,
  headerButtons,
  listLoading,
  detailLoading,
  showCreateChannelDialog,
  showEditChannelDialog,
  showCreateSecondAgentDialog,
  showCreateThirdAgentDialog,
  showEditSecondAgentDialog,
  showEditThirdAgentDialog,
  currentParentAgent,
  currentEditAgent,
  currentEditChannel,
  selectChannel,
  editChannel,
  createChannel,
  updateChannel,
  openCreateSecondAgentDialog,
  createSecondAgent,
  createThirdAgent,
  editAgent,
  updateSecondAgent,
  updateThirdAgent,
  toggleAgentExpand,
  addSubAgent,
  paginatedChannels,
  total,
  currentPage,
  pageSize,
  handlePageChange,
  getChannelAgents,
  getChannelAgentCount
} = useChannelManagement()
</script>

<template>
  <div class="app-container">
    <!-- 页面头部 -->
    <PageHeader
      title="渠道管理"
      subtitle="管理渠道服务商和多级代理商"
      :buttons="headerButtons"
    />

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧渠道列表 -->
      <div class="left-panel">
        <!-- 搜索框 -->
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索渠道服务商..."
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <!-- 渠道服务商列表标题 -->
        <div class="list-header">
          <h3>渠道服务商列表</h3>
        </div>

        <!-- 渠道卡片列表 -->
        <div class="channel-list" v-loading="listLoading">
          <template v-if="paginatedChannels.length > 0">
            <div
              v-for="channel in paginatedChannels"
              :key="channel.id"
              class="channel-card"
              :class="{ active: selectedChannel?.id === channel.id }"
              @click="selectChannel(channel)"
            >
              <div class="card-header">
                <div class="channel-info">
                  <el-icon class="channel-icon">
                    <User />
                  </el-icon>
                  <span class="channel-name">{{ channel.name }}</span>
                </div>
                <div class="card-actions">
                  <CustomTag
                    :text="channel.status === 'active' ? '合作中' : '已停用'"
                    :type="channel.status === 'active' ? 'success' : 'danger'"
                  />
                  <el-button
                    link
                    size="small"
                    @click.stop="editChannel(channel)"
                  >
                    <el-icon><Edit /></el-icon>
                  </el-button>
                </div>
              </div>
              <div class="card-content">
                <div class="info-item">
                  <span class="label">负责人：</span>
                  <span class="value">{{ channel.manager }}</span>
                </div>
                <div class="info-item">
                  <span class="label">联系电话：</span>
                  <span class="value">{{ channel.contactPhone }}</span>
                </div>
                <div class="info-item">
                  <span class="label">创建时间：</span>
                  <span class="value">{{ channel.createTime }}</span>
                </div>
                <div class="info-item">
                  <span class="label">下属代理：</span>
                  <span class="value">{{ getChannelAgentCount(channel.id) }} 个</span>
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <el-empty description="暂无渠道服务商" />
          </template>
        </div>

        <!-- 分页组件 -->
        <div class="pagination-container" v-if="total > 10">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            :total="total"
            layout="prev, pager, next"
            size="small"
            :background="true"
            @current-change="handlePageChange"
          />
        </div>
      </div>

      <!-- 右侧详情面板 -->
      <div class="right-panel" v-loading="detailLoading">
        <div v-if="selectedChannel" class="detail-content">
          <!-- 渠道详情头部 -->
          <div class="detail-header">
            <h2>{{ selectedChannel.name }}</h2>
            <el-button
              type="primary"
              size="small"
              class="theme-primary-button"
              @click="openCreateSecondAgentDialog"
            >
              <el-icon style="margin-right: 8px;"><Plus /></el-icon>
              添加二级代理
            </el-button>
          </div>

          <!-- 基本信息 -->
          <div class="detail-section">
            <div class="section-row">
              <div class="info-group">
                <label>渠道ID</label>
                <span>{{ selectedChannel.id }}</span>
              </div>
              <div class="info-group">
                <label>负责人</label>
                <span>{{ selectedChannel.manager }}</span>
              </div>
            </div>
            <div class="section-row">
              <div class="info-group">
                <label>联系电话</label>
                <span>{{ selectedChannel.contactPhone }}</span>
              </div>
              <div class="info-group">
                <label>创建时间</label>
                <span>{{ selectedChannel.createTime }}</span>
              </div>
            </div>
          </div>

          <!-- 下属代理结构 -->
          <div class="detail-section">
            <h3>下属代理结构</h3>
            <div v-if="getChannelAgents(selectedChannel.id).length > 0" class="agent-tree">
              <!-- 递归渲染代理树 -->
              <template v-for="agent in getChannelAgents(selectedChannel.id)" :key="agent.id">
                <!-- 二级代理 -->
                <div class="agent-item level-two">
                  <div class="agent-info">
                    <el-icon
                      class="expand-icon"
                      @click="toggleAgentExpand(agent)"
                    >
                      <ArrowDown v-if="agent.expanded" />
                      <ArrowRight v-else />
                    </el-icon>
                    <el-icon class="agent-icon blue">
                      <User />
                    </el-icon>
                    <span class="agent-name">{{ agent.name }}</span>
                    <CustomTag
                      :text="agent.levelText"
                      type="info"
                      size="small"
                    />
                    <CustomTag
                      :text="agent.status === 'active' ? '启用' : '禁用'"
                      :type="agent.status === 'active' ? 'primary' : 'danger'"
                      :color="agent.status === 'active' ? '#FFFFFF' : undefined"
                      :background-color="agent.status === 'active' ? '#000000' : undefined"
                      size="small"
                    />
                  </div>
                  <div class="agent-actions">
                    <el-button
                      link
                      size="small"
                      @click="editAgent(agent)"
                    >
                      <el-icon><Edit /></el-icon>
                    </el-button>
                  </div>
                </div>

                <!-- 展开状态下显示子代理和添加按钮 -->
                <div v-if="agent.expanded" class="sub-agents">
                  <!-- 显示已有的三级代理 -->
                  <div
                    v-for="child in agent.children"
                    :key="child.id"
                    class="agent-item level-three"
                  >
                    <div class="agent-info">
                      <el-icon class="agent-icon green">
                        <User />
                      </el-icon>
                      <span class="agent-name">{{ child.name }}</span>
                      <CustomTag
                        :text="child.levelText"
                        type="success"
                        size="small"
                      />
                      <CustomTag
                        :text="child.status === 'active' ? '启用' : '禁用'"
                        :type="child.status === 'active' ? 'primary' : 'danger'"
                        :color="child.status === 'active' ? '#FFFFFF' : undefined"
                        :background-color="child.status === 'active' ? '#000000' : undefined"
                        size="small"
                      />
                    </div>
                    <div class="agent-actions">
                      <el-button
                        link
                        size="small"
                        @click="editAgent(child)"
                      >
                        <el-icon><Edit /></el-icon>
                      </el-button>
                    </div>
                  </div>

                  <!-- 添加三级代理按钮（无论有没有子代理都显示一个） -->
                  <div class="add-agent-item level-three" @click="addSubAgent(agent)">
                    <el-icon class="add-icon">
                      <Plus />
                    </el-icon>
                    <span>添加三级代理</span>
                  </div>
                </div>
              </template>
            </div>
            <div v-else class="empty-agents">
              <p>暂无下属代理</p>
              <el-button
                type="primary"
                size="small"
                class="theme-primary-button"
                @click="openCreateSecondAgentDialog"
              >
                <el-icon style="margin-right: 8px;"><Plus /></el-icon>
                添加代理
              </el-button>
            </div>
          </div>
        </div>
        <div v-else class="empty-detail">
          <p>请选择一个渠道服务商查看详情</p>
        </div>
      </div>
    </div>

    <!-- 创建渠道服务商弹窗 -->
    <CommonCreateDialog
      v-model="showCreateChannelDialog"
      :config="channelDialogConfig"
      :extra-data="{
        channelType: '区域服务商',
        status: '合作中',
        cooperationStartDate: new Date().toISOString(),
        channelLevel: 1,
      }"
      @confirm="createChannel"
    />

    <!-- 编辑渠道服务商弹窗 -->
    <CommonCreateDialog
      v-model="showEditChannelDialog"
      :config="editChannelDialogConfig"
      :initial-data="currentEditChannel ? {
        name: currentEditChannel.name,
        manager: currentEditChannel.manager,
        phone: currentEditChannel.contactPhone,
        status: currentEditChannel.status,
      } : {}"
      @confirm="updateChannel"
    />

    <!-- 新增二级代理弹窗 -->
    <CommonCreateDialog
      v-model="showCreateSecondAgentDialog"
      :config="secondAgentDialogConfig"
      :extra-data="{
        channelId: selectedChannel?.id,
        status: 'active',
        level: 2,
        levelText: '二级代理',
        expandable: true,
        expanded: false,
        children: [],
      }"
      @confirm="createSecondAgent"
    />

    <!-- 新增三级代理弹窗 -->
    <CommonCreateDialog
      v-model="showCreateThirdAgentDialog"
      :config="thirdAgentDialogConfig"
      :extra-data="{
        parentAgentId: currentParentAgent?.id,
        channelId: currentParentAgent?.channelId,
        status: 'active',
        level: 3,
        levelText: '三级代理',
      }"
      @confirm="createThirdAgent"
    />

    <!-- 编辑二级代理弹窗 -->
    <CommonCreateDialog
      v-model="showEditSecondAgentDialog"
      :config="editSecondAgentDialogConfig"
      :initial-data="currentEditAgent ? {
        name: currentEditAgent.name,
        manager: currentEditAgent.manager || '',
        phone: currentEditAgent.phone || '',
        status: currentEditAgent.status,
      } : {}"
      @confirm="updateSecondAgent"
    />

    <!-- 编辑三级代理弹窗 -->
    <CommonCreateDialog
      v-model="showEditThirdAgentDialog"
      :config="editThirdAgentDialogConfig"
      :initial-data="currentEditAgent ? {
        name: currentEditAgent.name,
        manager: currentEditAgent.manager || '',
        phone: currentEditAgent.phone || '',
        status: currentEditAgent.status,
      } : {}"
      @confirm="updateThirdAgent"
    />
  </div>
</template>

<style lang="scss" scoped>
@import "./styles/index.scss";
</style>
